package com.servlets.user.role;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.core.GlobalConstants;
import com.core.protocols.IKVObject;
import com.core.protocols.IServiceLayerDelegate;
import com.model.mapparser.UserRoleMapParser;
import com.model.user.UserRole;
import com.servicelayer.user.UserRoleListLayer;
import com.servlets.TaskTrackerServlet;


public class UserRoleAdd
        extends TaskTrackerServlet
        implements IServiceLayerDelegate {


    private HttpServletResponse postResponse     = null;



    /**
     * 
     * 
     */



    private static final long   serialVersionUID = 1L;



    @SuppressWarnings("unchecked")
    @Override
    protected void doPost ( HttpServletRequest request,
                            HttpServletResponse response )
            throws ServletException, IOException {


        this.postResponse = response;

        UserRole template = null;
        Map <String, String[]> map = null;
        map = request.getParameterMap();
        template = UserRoleMapParser.fromMap(map);

        UserRoleListLayer roleListLayer = new UserRoleListLayer();
        roleListLayer.setLayerDelegate(this);


        try {
            UserRoleListLayer.createEntityWithTemplate(template, roleListLayer.getLayerDelegate(), null);
        } catch ( Exception e ) {

        }


    }



    @Override
    public <T> void responseResponseItemsList ( final List <T> items,
                                                final Object request,
                                                final Exception exception ) {

        if ( items == null ) {
            return;
        }

        T item = items.get(0);

        this.redirectItemIntoOpenServlet(item);


    }



    private <T> void redirectItemIntoOpenServlet ( T item ) {

        if ( this.postResponse == null ) {
            return;
        }

        String redirection = String.format("%s", GlobalConstants.SERVLET_ADMINISTRATION);

        if ( item != null ) {
            if ( item instanceof IKVObject ) {
                IKVObject kvObject = (IKVObject) item;
                String idValue = kvObject.idValue().toString();
                redirection = String.format("%s?%s", GlobalConstants.SERVLET_ROLEINFO, idValue);
            }
        }

        try {
            this.postResponse.sendRedirect(redirection);
        } catch ( IOException e ) {
            e.printStackTrace();
        }

    }


}
